
package comment

import (
	"strconv"
	"strings"
	"fmt"
	"html"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)


func adminList(page int, size int, condition map[string]string, pageUrl string) ([]map[string]string, string) {
	sql := Core.Sql("fuxiaohei_comments").Paged(page, size).Order("id DESC")
	sql2 := Core.Sql("fuxiaohei_comments")
	args := []interface {}{}
	if len(condition) > 0 {
		for k, v := range condition {
			sql.Where(k + " = ?")
			sql2.Where(k + " = ?")
			args = append(args, v)
		}
	}
	comments := Core.Db.All(sql.Select(), args...)
	counts := Core.Db.One(sql2.Count(), args...)
	if len(comments) < 1 {
		return comments, ""
	}
	tmpArticles := map[string]map[string]string{}
	for k, v := range comments {
		if tmpArticles[v["belong_id"]] == nil {
			tmpArticles[v["belong_id"]] = articleGetById(strings.Replace(v["belong_id"], "article-", "", -1))
		}
		comments[k]["article_title"] = tmpArticles[v["belong_id"]]["title"]
		comments[k]["article_slug"] = tmpArticles[v["belong_id"]]["slug"]
		comments[k]["avatar"] = Rt.Media.Gravatar(v["email"], "40")
	}
	count, _ := strconv.Atoi(counts["countNum"])
	return comments, Rt.Pager.Html(Rt.Pager.Calculate(page, size, count), pageUrl, 1)
}

func StatusGroup() map[string]string {
	sql := "SELECT count( * ) AS num ,status FROM fuxiaohei_comments GROUP BY status"
	data := Core.Db.All(sql)
	res := map[string]string{}
	for _, v := range data {
		res[v["status"]] = v["num"]
	}
	return res
}

func AddReply(authorId string, data map[string]string) map[string]string {
	data["content"] = html.EscapeString(data["content"])
	data["content"] = strings.Replace(data["content"], "\n", "<br/>", -1)
	user := userGetById(authorId)
	parent := GetParent(data["parent"])
	data["content"] = `<a class="comment-parent-name" href="#comment-` + parent["id"] + `">@` + parent["author"] + `</a>` + data["content"]
	sql := Core.Sql("fuxiaohei_comments", "author,email,url,content,add_time,belong_id,status,parent_id,user_id").Insert()
	id := Core.Db.Exec(sql, user["real_name"], user["email"], user["url"], data["content"], Rt.Time.Now(), parent["belong_id"], "approved", data["parent"], authorId)
	return GetOne(fmt.Sprint(id))
}

func GetParent(parentId string) map[string]string {
	sql := Core.Sql("fuxiaohei_comments", "id,author,belong_id").Where("id = ?").Select()
	return Core.Db.One(sql, parentId)
}

func GetOne(id string) map[string]string {
	sql := Core.Sql("fuxiaohei_comments").Where("id = ?").Select()
	comment := Core.Db.One(sql, id)
	comment["avatar"] = Rt.Media.Gravatar(comment["email"], "40")
	return comment
}

func DeleteOne(id string) {
	sql := Core.Sql("fuxiaohei_comments").Where("id = ?").Delete()
	Core.Db.Exec(sql, id)
}

func UpdateStatus(comment string, status string) {
	sql := Core.Sql("fuxiaohei_comments", "status").Where("id = ?").Update()
	Core.Db.Exec(sql, status, comment)
}
